<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-divider orientation="left" style="font-weight: bold">基础信息</a-divider>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户编号"
            >
              <a-input-search
                v-decorator="['custCode',validatorRules.input]" placeholder="请选择客户"
                :disabled="disableSubmit"
                readOnly enter-button @search="custSearch('custCode')"/>
              <a-input type="hidden" v-decorator="['custCode',validatorRules.userCode]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="客户名称"
            >
              <a-input placeholder="请输入" :disabled="true" v-decorator="['custName',validatorRules.input]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="收货地址"
            >
              <a-input-search :disabled="disableSubmit" v-decorator="['addressDetailed',validatorRules.addressDetailed]"
                              placeholder="请选择收货地址"
                              readOnly enter-button @search="custSearch0('addressCode')"/>
              <a-input type="hidden" v-decorator="['addressCode']"/>
              <a-input type="hidden" v-decorator="['addressRegion']"/>
              <a-input type="hidden" v-decorator="['consignee']"/>
              <a-input type="hidden" v-decorator="['consigneeCall']"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="提货点名称"
            >
              <a-input-search
                v-decorator="['pupName',validatorRules.input]" placeholder="请选择提货点"
                :disabled="disableSubmit"
                readOnly enter-button @search="custSearch1('pupCode')"/>
              <a-input type="hidden" v-decorator="['pupCode',validatorRules.userCode]"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="退货类型"
            >
              <cn-dict-select-tag
                placeholder="实物退"
                triggerChange
                dictCode="oms_business_type"
                :disabled="disableSubmit"
                :options="{value:'dictDataCode',label:'dictDataDesc'}"
                v-decorator.trim="['businessTypeCode',{initialValue:'WHOLESALE_JXS'},validatorRules.select]"
                @change="handelDictCode"
              />
              <!--              <a-input type="hidden" v-decorator="['businessType']"/>-->
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="物流模式"
            >
              <a-select
                :disabled="disableSubmit"
                v-decorator="['select',{ initialValue:'1',rules: [{ required: true, message: '' }] },]"
                placeholder="速冻">
                <a-select-option value="1">
                  速冻
                </a-select-option>
                <a-select-option value="2">
                  常温
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              required="true"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="oms订单编码"
            >
              <a-input placeholder="请输入" :disabled="disableSubmit" v-decorator="['omsOrderCode',validatorRules.input]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <!-- 活动明细 -->
    <a-divider orientation="left" style="font-weight: bold">产品信息</a-divider>
    <cn-select-goods selectButtonText="添加产品"
                     name="商品"
                     :inputs="false"
                     searchIcon=""
                     :queryParams="{customerCode: form.getFieldValue('customerCode')}"
                     :buttons="true"
                     :multiple="true"
                     rowKey="goodsCode"
                     :returnName="true"
                     listUrl="/goods/cnGoods/findPcPageList"
                     :disabled="disableSubmit||!form.getFieldValue('customerCode')"
                     @select="selectGoodsBp"
                     class="form-input">
    </cn-select-goods>
    <div style="margin-bottom: 10px"></div>
    <a-table
      ref="table"
      size="middle"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      class="Table j-table-force-nowrap"
      @change="handleTableChange">
       <span slot="dataTypeCode" slot-scope="text,row,index">
          <a-select
            :disabled="disableSubmit"
            v-model="row.dataTypeCode"
            placeholder="行类型">
            <a-select-option value="1">
              本品
            </a-select-option>
            <a-select-option value="2">
              货补
            </a-select-option>
            <a-select-option value="3">
              赠品
            </a-select-option>
            <a-select-option value="4">
              搭赠
            </a-select-option>
          </a-select>
      </span>
      <span slot="quantity" slot-scope="text,row,index">
         <a-input-number :disabled="disableSubmit" size="mini" v-model="row.quantity" :min="0" precision="0" style="width:100px !important;" @change="handleChangeNum(index)"></a-input-number>
      </span>
      <span slot="action" slot-scope="text, record,index"  >
              <a-popconfirm :disabled="disableSubmit" title="确定删除吗?" @confirm="() => handleDelete(index)">
                      <a :style="{color:disableSubmit?'grey':'red'} ">删除</a>
              </a-popconfirm>
            </span>
    </a-table>
    <div style="margin-top:20px">
      <a-form>
        <a-col :md="24" :sm="24">
          <a-form-item
            :labelCol="{ xs: { span:10 }, sm: { span: 1}}"
            :wrapperCol="{ xs: { span:10 }, sm: { span: 22}}"
            label="备注"
            style="margin-left: 10px;"
          >
            <a-textarea :disabled="disableSubmit" v-decorator="['remarks', ]"/>
          </a-form-item>
        </a-col>
      </a-form>
    </div>
    <!-- 添加产品弹窗组件 -->
    <my-shuttle-modal
      ref="shuttleModal"
      :title="modelname"
      :searchConfig="searclist"
      :columns="columnslist"
      :columns2="columnslist2"
      leftUrl=""
      @chooseOk="chooseOk">
    </my-shuttle-modal>
    <!--  编号查询弹窗组件  -->
    <proChose :name="modelname" ref="prochoose" v-bind="modalProps" @okbro="okbropro"></proChose>
    <orderspModal :name="modelname" ref="orderspModal" v-bind="modalProps" @okbro="okbropro"></orderspModal>
  </j-modal>
</template>

<script>
import orderspModal from './orderspModal.vue'
import { getAction, httpAction, postAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import { twoDecimalPlaces } from '@/utils/util'
import proChose from '@comp/cn-components/ProChose'    //编号查询弹窗组件
import myShuttleModal from '@/components/cn-components/CnShuttleModal'  //添加产品弹窗组件
import { PageListMixin } from '@/mixins/PageListMixin'
import CnSelectGoods from '@comp/cn-select-popup/CnSelectGoods'

export default {
  name: 'TpmActSpecialModal',
  components: {
    proChose,       //编号查询弹窗组件
    myShuttleModal, //添加产品弹窗组件
    orderspModal,
    CnSelectGoods
  },
  mixins: [PageListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      visible1: false,
      disableSubmit:false,
      model: {},
      modelname: '关联',
      searclist: [],
      columnslist: [],
      columnslist2: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '产品编号',
          align: 'center',
          dataIndex: 'cx'
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'cx'
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'cx'
        },
      ],
      tempUuid: '',
      showterm: false,
      showorg: false,
      columns1: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '车型',
          align: 'center',
          dataIndex: 'cx'
        },
        {
          title: '有效利用体积（立方米）',
          align: 'center',
          dataIndex: 'tj'
        },
        {
          title: '折合件数区间（件）',
          align: 'center',
          dataIndex: 'qj'
        },
      ],
      dataSource1: [
        {
          cx: '4.2米',
          tj: '5-14',
          qj: '200-550'
        },
        {
          cx: '6.8米米',
          tj: '19-23',
          qj: '750-900'
        },
        {
          cx: '7.2米',
          tj: '20-33',
          qj: '800-1300'
        },
        {
          cx: '8.6米',
          tj: '32.5-36.4',
          qj: '1250-1400'
        },
        {
          cx: '9.6米',
          tj: '39-42.9',
          qj: '1500-1650'
        },
        {
          cx: '13.7米',
          tj: '52-59.8',
          qj: '2000-2300'
        }
        , {
          cx: '15米',
          tj: '57.2-70.2',
          qj: '2200-2700'
        }
      ],
      columns: [
        {
          title: '行号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },

        {
          title: '产品编号',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '产品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unitDesc',
        },
        {
          title: '单位转化率',
          align: 'center',
          dataIndex: 'unitConversionRate',
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'dataTypeCode',
          scopedSlots: { customRender: 'dataTypeCode' }
        },
        {
          title: '单价',
          align: 'center',
          dataIndex: 'originalPrice',
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity',
          scopedSlots: { customRender: 'quantity' }
        },
        {
          title: '总金额',
          align: 'center',
          dataIndex: 'totalAmount',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],

      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      tabs: {
        activeKey: 'global',
        global: {
          key: 'global',
          columns: [],
          dataSource: []
        }
      },
      dataSource: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        input: { rules: [{ required: true, message: '' }] },
        userCode: { rules: [{ required: true, message: '' }] },
        select: { rules: [{ required: true, message: '' }] }
      },
      url: {
        add: window._CONFIG['domianDmsURL'] + '/order/dmsOrderBackHead/saveOrUpdate',
        edit: window._CONFIG['domianDmsURL'] + '/order/dmsOrderBackHead/saveOrUpdate',
      }
    }
  },
  created() {
  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    }
  },
  methods: {
    moment,
    handelDictCode(e,list){
      console.log(e,list)
      this.form.setFieldsValue({
        businessType: list.dictDataDesc,
      })
    },
    async okbropro(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      if (status == 'custCode') {
        // 查询客户信息
        this.form.setFieldsValue({
          custCode: objs.custCode,
          custName: objs.custName,
        })
      } else if (status == 'addressCode') {
        this.form.setFieldsValue({
          addressCode: objs.receivingAddressCode,
          addressDetailed: objs.addressDetailed,
          addressRegion: objs.receivedGoodsArea,
          consignee: objs.receivedGoodsName,
          consigneeCall: objs.receivedGoodsTel
        })
      } else if (status == 'pupCode') {
        this.form.setFieldsValue({
          pupCode: objs.pupCode,
          pupName: objs.pupName,
        })
      }
    },
    handleChangeNum(index){
      this.dataSource[index].totalAmount = twoDecimalPlaces(this.dataSource[index].originalPrice * this.dataSource[index].quantity)
    },
    handleSelectProduct(e) {
      this.form.setFieldsValue({ 'productName': e[0].productName })
    },
    handleSelectCode() {
      this.$refs.CodeConfigModal.showModal(4)
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (this.model.id) {
        this.dataSource = this.model.orderBackItemVoList || []
      }
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
        //时间格式化
      })

    },
    // 选择本品
    async selectGoodsBp(rows) {
      if (rows) {
        this.dataSource = rows.map(detail => {
          return {
            productCode: detail.productCode || detail.goodsCod,
            productName: detail.productName,
            goodsCode: detail.goodsCode || detail.productCode,
            goodsName: detail.goodsName,
            originalPrice: detail.price,
            unitDesc: detail.unitDesc,
            unitConversionRate: detail.unitConversionRate,
            totalAmount: 0,
            dataType: '本品',
            dataTypeCode: '1',
            quantity: 0
          }
        })
      }
    },
    close() {
      this.$emit('close')
      this.dataSource = []
      this.visible = false
    },
    handleOk1() {
      this.visible1 = false
    },
    showModal() {
      this.visible1 = true
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          httpurl += this.url.add
          method = 'post'
          let formData = Object.assign(this.model, values)
          this.fromOrderLineNo
          this.dataSource.forEach((item,index)=>{
            item.posnr = index+1
          })
          formData.orderBackItemVoList = this.dataSource
          formData.chargebackQuantity = twoDecimalPlaces(this.dataSource.reduce((all, item) => all + (item.quantity || 0), 0))
          formData.chargebackAmount = twoDecimalPlaces(this.dataSource.reduce((all, item) => all + (item.totalAmount || 0), 0))
          that.confirmLoading = true
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    handleCancel() {
      this.close()
      this.showterm = false
    },
    changeTerm(val) {
      if (val != undefined) {
        if (val === '' || val === '0') {
          this.showterm = false
          this.showorg = true
        } else {
          this.showterm = true
          this.showorg = false
        }
      }
    },
    custSearch(status) {
      this.modelname = '客户'
      this.$refs.prochoose.rowKey = 'custCode'
      let formconfig = [
        {
          key: 'custCode',
          label: '客户编号'
        },
        {
          key: 'custName',
          label: '客户名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '客户编号',
            align: 'center',
            dataIndex: 'custCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '客户名称',
            align: 'center',
            dataIndex: 'custName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/customerController/findPageList',
        multiple: false,
        columW: 8
      }
      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          custCode: this.form.getFieldValue('custCode'),
          custName: this.form.getFieldValue('custName')
        }]
      }
      this.name = '客户'
      this.$refs.prochoose.isorter = { status: 1 }
      this.$refs.prochoose.edit(formconfig, tableconfig, 'custCode', 'custName', dataSource)
    },
    custSearch0(status) {
      this.modelname = '收货地址'
      // console.log('数据',status)
      this.$refs.prochoose.rowKey = 'receivingAddressCode'
      let formconfig = [
        {
          key: 'receivingAddressCode',
          label: '收货地址编号'
        },
        {
          key: 'addressDetailed',
          label: '收货地址名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '收货地址编号',
            align: 'center',
            dataIndex: 'receivingAddressCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '收货地址名称',
            align: 'center',
            dataIndex: 'addressDetailed',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/receivedgoodsaddress/cnReceivedGoodsAddress/findPageList',
        multiple: false,
        columW: 8
      }

      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          receivingAddressCode: this.form.getFieldValue('addressCode'),
          addressDetailed: this.form.getFieldValue('addressDetailed')
        }]
      }
      this.name = '客户'
      this.$refs.prochoose.isorter = { status: 1, customerCode: this.form.getFieldValue('customerCode'), }
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'addressDetailed', dataSource)
    },

    custSearch1(status) {
      this.modelname = '提货点'
      this.$refs.prochoose.rowKey = 'pupCode'
      let formconfig = [
        {
          key: 'pupCode',
          label: '提货点编号'
        },
        {
          key: 'pupName',
          label: '提货点名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '提货点编号',
            align: 'center',
            dataIndex: 'pupCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '提货点名称',
            align: 'center',
            dataIndex: 'pupName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/pupconfig/cnPupConfig/findPageList',
        multiple: false,
        columW: 8
      }

      let dataSource = []
      if (this.form.getFieldValue('pupCode')) {
        dataSource = [{
          pupCode: this.form.getFieldValue('pupCode'),
          pupName: this.form.getFieldValue('pupName')
        }]
      }
      this.name = '客户'
      this.$refs.prochoose.isorter = { status: 1, customerCode: this.form.getFieldValue('pupCode'), }
      this.$refs.prochoose.edit(formconfig, tableconfig, status, 'addressDetailed', dataSource)
    },

    handleDelete(index) {
      this.dataSource.splice(index, 1)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-modal-body {
  padding-top: 0 !important;
}

.ant-calendar-picker, .ant-input-number {
  width: 100% !important;
}
</style>
